package main.bean;

import main.protobuf.Common;
import main.service.MessageId;
import main.utils.GameUtils;
import threadPool.task.ITask;
import threadPool.thread.IMessageExecutor;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by JinMiao
 * 2019-06-26.
 */
public class Room implements Runnable, ITask {
    Map<Integer,Player> players = new ConcurrentHashMap<>();

    private IMessageExecutor iMessageExecutor;

    private volatile boolean executed;

    public Map<Integer, Player> getPlayers() {
        return players;
    }

    public void setPlayers(Map<Integer, Player> players) {
        this.players = players;
    }

    public IMessageExecutor getiMessageExecutor() {
        return iMessageExecutor;
    }

    public void setiMessageExecutor(IMessageExecutor iMessageExecutor) {
        this.iMessageExecutor = iMessageExecutor;
    }

    public void execute() {
        Common.FightMessageS2C.Builder builder = Common.FightMessageS2C.newBuilder();
        //合并消息
        for (Player player : players.values()) {
            if(player.getInputPackages().size()==0){
                continue;
            }

            Common.InputPackages.Builder inputPackages = Common.InputPackages.newBuilder();
            inputPackages.addAllInputPackages(player.getInputPackages());

            builder.putPlayerInput(player.getId(),inputPackages.build());
            player.getInputPackages().clear();
        }
        Message message = new Message();
        message.setActionId(MessageId.FightMessage_S2C);
        message.setBody(builder.build());
        GameUtils.sendTo(message,players.values());
    }

    @Override
    public void run() {
        iMessageExecutor.execute(this);
    }
}
